package hls.plugin.qywx.service;

import com.google.gson.Gson;
import hls.plugin.qywx.model.*;
import hls.plugin.qywx.util.WeChatParamesUtil;
import hls.plugin.qywx.util.WeChatUtil;
import net.sf.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class QywxSend {
    private static String sendMessage_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
    /**
     * 推送文本类型
     *
     * @param uid
     * @param content
     * @return
     */
    public String sendMessageByText(String uid, String content, String accessToken) {

        String status = "success";

        // 1.获取access_token:根据企业id和应用密钥获取access_token,并拼接请求url
        //不推荐使用，token会有过期时间，不能时时一直请求，可能企业微信会被锁
        //String accessToken = WeChatUtil.getAccessToken(WeChatParamesUtil.corpId, WeChatParamesUtil.corpsecret).getToken();
        // 2.获取发送对象，并转成json
        Gson gson = new Gson();
        TextMessage message = new TextMessage();

        // 1.1非必需
        message.setTouser(uid); // 不区分大小写
        //message.setToparty("1");
        //message.getTouser(totag);
        // txtMsg.setSafe(0);
        // 1.2必需
        message.setMsgtype("text");
        message.setAgentid(WeChatParamesUtil.agentId);
        Text text = new Text();
        text.setContent(content);
        message.setText(text);
        String jsonMessage = gson.toJson(message);

        // 3.获取请求的url
        String url = sendMessage_url.replace("ACCESS_TOKEN", accessToken);
        // 4.调用接口，发送消息
        //JSONObject jsonObject = WeChatUtil.httpRequest(url, "POST", jsonMessage);
        JSONObject jsonObject = null;
        jsonObject = WeChatUtil.httpRequest(url, "POST", jsonMessage);

        // 4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                status = "消息发送失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg");
                //status = "fail";
            }
        }
        return status;
    }


    /**
     * 推送类型为文本卡片类型
     *
     * @param uid
     * @param title
     * @param description
     * @param jumpUrl
     * @param accessToken
     * @return
     */
    public String sendMessageByTextCard(String uid, String title, String description, String jumpUrl, String accessToken) {

        String status = "success";
        // 1.获取access_token:根据企业id和应用密钥获取access_token,并拼接请求url
        //不推荐使用，token会有过期时间，不能时时一直请求，可能企业微信会被锁
        //String accessToken = WeChatUtil.getAccessToken(WeChatParamesUtil.corpId, WeChatParamesUtil.corpsecret).getToken();
        // 2.获取发送对象，并转成json
        Gson gson = new Gson();
        TextCardMessage message = new TextCardMessage();

        // 1.1非必需
        message.setTouser(uid); // 不区分大小写
        //message.setToparty("1");
        //message.getTouser(totag);
        // txtMsg.setSafe(0);
        message.setMsgtype("textcard");
        message.setAgentid(WeChatParamesUtil.agentId);

        TextCard textCard = new TextCard();
        textCard.setTitle(title);
        textCard.setDescription(description);
        textCard.setUrl(jumpUrl);
        message.setTextcard(textCard);

        String jsonMessage = gson.toJson(message);

        // 3.获取请求的url
        String url = sendMessage_url.replace("ACCESS_TOKEN", accessToken);
        // 4.调用接口，发送消息
        JSONObject jsonObject = WeChatUtil.httpRequest(url, "POST", jsonMessage);
        // 4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                System.out.println("消息发送失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg"));
                status = "fail";
            }
        }
        return status;
    }

    /**
     * 小程序推送类型
     *
     * @param uid
     * @param content
     * @param jumpUrl
     * @param accessToken
     * @return
     */
    public String sendMessageByTextCardByMiniProgram(String uid, String title, String content, String jumpUrl, String accessToken) {

        String status = "success";
        // 1.获取access_token:根据企业id和应用密钥获取access_token,并拼接请求url
        //不推荐使用，token会有过期时间，不能时时一直请求，可能企业微信会被锁
        //String accessToken = WeChatUtil.getAccessToken(WeChatParamesUtil.corpId, WeChatParamesUtil.corpsecret).getToken();
        // 2.获取发送对象，并转成json
        Gson gson = new Gson();
        MiniProgramMessage message = new MiniProgramMessage();

        // 1.1非必需
        message.setTouser(uid); // 不区分大小写
        //message.setToparty("1");
        //message.getTouser(totag);
        message.setMsgtype("miniprogram_notice");
        //message.setAgentid(WeChatParamesUtil.agentId);

        MiniProgram miniProgram = new MiniProgram();
        miniProgram.setAppid(WeChatParamesUtil.appId);
        miniProgram.setPage(jumpUrl);
        miniProgram.setTitle(title);
        //miniProgram.setEmphasis_first_item("true");

        ContentItem[] arr = new ContentItem[1];
        ContentItem contentItem = new ContentItem();
        contentItem.setKey("内容摘要");
        contentItem.setValue(content);
        arr[0] = contentItem;

        //miniProgram.setContent_item(contentItem);
        miniProgram.setContent_item(arr);
        miniProgram.setEnable_id_trans(0);
        miniProgram.setEnable_duplicate_check(0);

        message.setMiniprogram_notice(miniProgram);

        String jsonMessage = gson.toJson(message);

        // 3.获取请求的url
        String url = sendMessage_url.replace("ACCESS_TOKEN", accessToken);
        // 4.调用接口，发送消息

        JSONObject jsonObject = WeChatUtil.httpRequest(url, "POST", jsonMessage);

        // 4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                status = "消息发送失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg");
                //status = "fail";
            }
        }
        return status;

    }

    public String sendMessage(String uid, String content, String jumpUrl, String sendType, String accessToken) {

        Map<String, String> titleMap = new HashMap<String, String>();
        titleMap.put(WeChatParamesUtil.JC_PROJECT_APPROVE_WFL, "项目审批待办通知");//项目审批待办
        titleMap.put(WeChatParamesUtil.JC_CONTRACT_WFL, "合同审批待办通知");//合同审批待办
        titleMap.put(WeChatParamesUtil.VISIT_REPORT_ALLOCATED, "资产巡视任务待办通知");//资产巡视

        String successStatus;
        //如果是以上三种待办使用小程序推送类型，系统公告用文本消息类型
        if (titleMap.containsKey(sendType)) {
            successStatus = sendMessageByTextCardByMiniProgram(uid, titleMap.get(sendType), content, jumpUrl, accessToken);
        } else {
            String showContent = "你有一条系统公告待查看：" + content;
            successStatus = sendMessageByText(uid, showContent, accessToken);
        }

        return successStatus;
    }

    public static void main(String[] args) {
        String token = "tbsu8JwotWzGIdMHYatGxL1c6KdgU-tuXsMcMVmxwKJUDf4OY9kC9fJYQMwZn9_yFErtsBKmSnBf6wGVtWlWFabQL4F0sprh6U1no1CbsKouioG0sa-IDabqXNplOgqXBwsM0S2obpy0BhUFnnSmIzFkH6z4WaIP1zLZd7-ATJOb06ws_5aYmlWgSLnO0xYGRJaDxGaovf_s9x_iRm-HUQ";
        System.out.println("a类错误信息");
        String a = new QywxSend().sendMessageByTextCardByMiniProgram("liuyuhao", "测试标题啊", "1", "11", token);
        System.out.println("a: " + a);

        System.out.println("b类错误");
        String b = new QywxSend().sendMessageByText("liuyuhao", "系统公告", token);

        //嘿嘿
        System.out.println("b: " + b);
    }

}
